import Vue from 'vue';

/******************** 定义类 ***************************************************************/
/*
    管理员类
 */
function Page(action, action_data, callback) {
    this.action = action || "";
    this.page_size = 10;
    this.current_page = 1;
    this.total = 0;
    this.order_by = {};
    this.list = [];
    this.action_data = action_data || {};  
    this.callback = callback || function(){}
}

// 将对象序列化为一个json对象，可以用于http请求或对象复制
Page.prototype.serialize = function() {
    return Object.assign({
        current_page: this.current_page,
        page_size: this.page_size,
        order_by: this.order_by
    }, this.action_data);
}

// 用json数据为对象属性赋值
Page.prototype.parse = function(data) {
    this.current_page = data.current_page;
    this.page_size = data.page_size;
    this.total = data.total;
    this.list = data.list;
}

// 暂时将属性存起来，做一次备份
Page.prototype.storageValue = function() {
    this.storage.action_data = this.action_data;
    this.action_data = {};
    this.storage = this.serialize();
    this.action_data = this.storage.action_data;
    this.storage.total = this.total;
    this.storage.list = this.list;
}

// 用备份的数据覆盖现有数据
Page.prototype.applyStorageValue = function() {
    if(this.storage) {
        this.parse(this.storage);
    }
}

Page.prototype.getData = function(callback) {
    this.callback = callback || this.callback;
    Vue.prototype.api.post(this.action, this.serialize(), res => {
        this.parse(res.page);
        this.callback(res);
    });
}

Page.prototype.exportExcel = function() {
    Vue.prototype.api.getResource(this.action, Object.assign(this.serialize(), { excel: true }));
}


// ******************** 类静态属性与方法 **********************************************
// 解析json数据，返回一个对象
Page.parse = function(data) {
    var o = new Page();
    o.parse(data);
    return o;
}

// 解析json数组，返回对象数组
Page.parseList = function(list) {
    var len = list.length;
    var arr = new Array(len);
    for(var i = 0; i < len; i++) {
        arr[i] = Page.parse(list[i]);
    }
    return arr;
}

// ******************** 数据库存储方法 **********************************************
// Page.prototype.save = function(callback) {
//     var that = this;
//     var action = this.mode == "add" ? "article_add" : "article_modify";
//     api.post(action, this.serialize(), function(res) {
//         that.id = res.id;
//         if(callback) callback();
//     });
// }



// ******************** 导出 **********************************************
export default Page